package com.yunxi.poc.starbucks.util;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shiyuan.xlc
 * @since 2021-08-09
 */
public class DateUtil {
    /**
     * 获取时间区间对【30分钟一对】
     *
     * @param dateTime
     * @param offset   0-当前时间对，-1-上一个时间对，1-下一个时间对
     * @return
     */
    public static List<LocalDateTime> getTimePair(LocalDateTime dateTime, int offset) {
        List<LocalDateTime> res = new ArrayList<>();    // [start,end]
        if (offset == 0) {
            if (dateTime.getMinute() >= 30 && dateTime.getSecond() > 0) {
                res.add(dateTime.withMinute(30).withSecond(0));
                res.add(dateTime.plusMinutes(30).withMinute(0).withSecond(0));
            } else {
                res.add(dateTime.withMinute(0).withSecond(0));
                res.add(dateTime.withMinute(30).withSecond(0));
            }
        }

        if (offset == -1) {
            if (dateTime.minusMinutes(30).getMinute() < 30) {
                res.add(dateTime.minusMinutes(30).withMinute(0).withSecond(0));
                res.add(dateTime.minusMinutes(30).withMinute(30).withSecond(0));
            } else {
                res.add(dateTime.minusMinutes(30).withMinute(30).withSecond(0));
                res.add(dateTime.withMinute(0).withSecond(0));
            }
        }

        if (offset == 1) {
            if (dateTime.plusMinutes(30).getMinute() >= 30 && dateTime.plusMinutes(30).getSecond() > 0) {
                res.add(dateTime.plusMinutes(30).withMinute(30).withSecond(0));
                res.add(dateTime.plusHours(1).withMinute(0).withSecond(0));
            } else {
                res.add(dateTime.plusMinutes(30).withMinute(0).withSecond(0));
                res.add(dateTime.plusMinutes(30).withMinute(30).withSecond(0));
            }
        }

        return res;
    }

    public static List<List<LocalDateTime>> getTimePairAfter(LocalDateTime dateTime) {
        List<List<LocalDateTime>> res = new ArrayList<>();    // [start,end]
        List<LocalDateTime> beginPair = DateUtil.getTimePair(dateTime, 0);
        res.add(beginPair);
        while (beginPair.get(1).toLocalDate().isEqual(dateTime.toLocalDate())) {
            beginPair = DateUtil.getTimePair(beginPair.get(1).plusSeconds(1), 0);
            res.add(beginPair);
        }
        return res;
    }

}